import router, { asyncRoutes, editorRoutes, constantRoutes } from '@/router'


/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  // if (route.meta && route.meta.roles) {
  //   return roles.some(role => route.meta.roles.includes(role))
  // } else {
  //   return true
  // }
  if (roles.menus && route.name) {
    return roles.menus.some(role => {
      return route.name.toLowerCase() === role.toLowerCase()
    })
  } else {
    return false
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  // console.log('被筛选的权限：' + roles)
  // console.log('路由:' + routes)
  const res = []
  // routes = asyncRoutes
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      // console.log('被筛选的路由'+tmp)
      res.push(tmp)
    }
  })
  // console.log('被筛选的路由' + res.length)
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, data) {
    return new Promise(resolve => {
      let accessedRoutes = []
      // if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes
      //   // accessedRoutes = asyncRoutes || []
      // } else {
      //   accessedRoutes = asyncRouterMap
      //   // 展示先这样
      //   accessedRoutes = editorRoutes || []
      //   // accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
      const { roles } = data
      // console.log('权限：',roles)
      // 动态构造权限列表
      accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // accessedRoutes = asyncRoutes
      commit('SET_ROUTES', accessedRoutes)
      // commit('SET_ROUTES', asyncRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
